// src/utils/tabPersistence.ts
import { useEffect } from 'react';

// 状态管理，只处理不在菜单中的页面
const tabStates: Record<string, any> = {};


// 深度比较对象
export const deepEqual = (a: any, b: any): boolean => {
    if (a === b) return true;
    
    if (typeof a !== 'object' || a === null || 
        typeof b !== 'object' || b === null) {
      return false;
    }
    
    const keysA = Object.keys(a);
    const keysB = Object.keys(b);
    
    if (keysA.length !== keysB.length) return false;
    
    for (const key of keysA) {
      if (!keysB.includes(key)) return false;
      
      if (typeof a[key] === 'object' && typeof b[key] === 'object') {
        if (!deepEqual(a[key], b[key])) return false;
      } else if (a[key] !== b[key]) {
        return false;
      }
    }
    
    return true;
  };
  // 状态持久化函数
export const persistTabState = (tabKey: string, state: any) => {
    try {
      tabStates[tabKey] = state;
      sessionStorage.setItem('tabStates', JSON.stringify(tabStates));
    } catch (error) {
      console.error('状态保存失败:', error);
    }
  };
  
  /**
   * 获取选项卡状态
   */
  export const getTabState = (tabKey: string) => {
    try {
      // 1. 尝试从内存获取
      if (tabStates[tabKey]) return tabStates[tabKey];
      
      // 2. 尝试从 sessionStorage 恢复
      const savedStates = sessionStorage.getItem('tabStates');
      if (savedStates) {
        const parsed = JSON.parse(savedStates);
        return parsed[tabKey] || null;
      }
      
      return null;
    } catch (error) {
      console.error('获取选项卡状态失败:', error);
      return null;
    }
  };
  
  /**
   * 移除选项卡状态
   */
  export const removeTabState = (tabKey: string) => {
    try {
      // 从内存移除
      delete tabStates[tabKey];
      
      // 更新sessionStorage
      const savedStates = sessionStorage.getItem('tabStates');
      if (savedStates) {
        const parsed = JSON.parse(savedStates);
        delete parsed[tabKey];
        sessionStorage.setItem('tabStates', JSON.stringify(parsed));
      }
    } catch (error) {
      console.error('移除选项卡状态失败:', error);
    }
  };
  

  export const cleanupExpiredTabStates = () => {
    const now = Date.now();
    const savedStates = sessionStorage.getItem('tabStates');
    
    if (savedStates) {
      try {
        const parsed = JSON.parse(savedStates);
        let changed = false;
        
        // 清理超过1天的状态
        Object.keys(parsed).forEach(key => {
          if (key.startsWith('state-') && key.includes('-')) {
            const timestamp = parseInt(key.split('-')[1]);
            if (now - timestamp > 24 * 60 * 60 * 1000) {
              delete parsed[key];
              changed = true;
            }
          }
        });
        
        if (changed) {
          sessionStorage.setItem('tabStates', JSON.stringify(parsed));
        }
      } catch (error) {
        console.error('清理过期状态失败:', error);
      }
    }
  };



/**
 * 获取当前活动选项卡
 */
export const setActiveTabKey = (tabKey: string) => {
    sessionStorage.setItem('currentTabKey', tabKey);
};

/**
 * 获取当前活动选项卡
 */
export const getActiveTabKey = () => {
    return sessionStorage.getItem('currentTabKey');
};

/**
 * 清理所有选项卡状态
 */
export const clearAllTabStates = () => {
  // 清空内存
  Object.keys(tabStates).forEach(key => delete tabStates[key]);
  
  // 清空sessionStorage
  sessionStorage.removeItem('tabStates');
  sessionStorage.removeItem('currentTabKey');
};